package repositories

import (
	"fmt"
	"pass-tree/internal/logic/models"
)

// 获取密码数据列表
func GetPasswordData(categoryId int) ([]models.Password, error) {
	ret, err := DB.Query("select * from password where category_id=? order by id desc", categoryId)
	if err != nil {
		return nil, err
	}
	var pass []models.Password
	for ret.Next() {
		var pas models.Password
		_ = ret.Scan(&pas.Id, &pas.Category_id, &pas.Name, &pas.Username, &pas.Password, &pas.Desc, &pas.Status, &pas.Del, &pas.CustomInputType)
		/* if err != nil {
			continue
		} */
		// pas.CustomContent = &GetInputContent(pas.Id)
		inputContent, err := GetInputContent(pas.Id)
		if err != nil {
			fmt.Println("获取密码数据失败", err)
		}
		pas.CustomContent = inputContent
		pass = append(pass, pas)
	}
	return pass, nil
}

// 获取一条密码数据
func GetPassword(id int) (models.Password, error) {
	ret, err := DB.Query("select * from password where id=?", id)
	if err != nil {
		return models.Password{}, err
	}
	var pas models.Password
	if ret.Next() {
		_ = ret.Scan(&pas.Id, &pas.Category_id, &pas.Name, &pas.Username, &pas.Password, &pas.Desc, &pas.Status, &pas.Del)
	}

	return pas, nil
}

func SavePassword(password *models.Password) error {
	ret, err := DB.Exec("insert into password (category_id,name,username,password,desc,input_type) values (?,?,?,?,?,?)", password.Category_id, password.Name, password.Username, password.Password, password.Desc, password.CustomInputType)
	if err != nil {
		return err
	}
	lastInsertId, err := ret.LastInsertId()
	if err != nil {
		return err
	}
	password.Id = int(lastInsertId)

	for i, _ := range password.CustomContent {
		password.CustomContent[i].Password_id = password.Id
	}
	BatchSaveInputContent(password.CustomContent)

	return nil
}

func UpdatePassword(password *models.Password) error {
	ret, err := DB.Exec("update password set name=?,username=?,password=?,desc=? where id = ?", password.Name, password.Username, password.Password, password.Desc, password.Id)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected()
	if err != nil {
		return err
	}

	for _, v := range password.CustomContent {
		if v.Id == 0 {
			SaveInputContent(v)
		} else {
			UpdateInputContent(&v)
		}
	}
	return nil
}

func DeletePassword(id int) error {
	ret, err := DB.Exec("delete from password where id=?", id)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected()
	if err != nil {
		return err
	}
	return nil
}

// 搜索密码数据列表
func SearchPasswordData(keyword string) ([]models.Password, error) {
	ret, err := DB.Query("select * from password where name like '%" + keyword + "%' or username like '%" + keyword + "%' order by id desc")
	if err != nil {
		return nil, err
	}
	var pass []models.Password
	for ret.Next() {
		var pas models.Password
		_ = ret.Scan(&pas.Id, &pas.Category_id, &pas.Name, &pas.Username, &pas.Password, &pas.Desc, &pas.Status, &pas.Del, &pas.CustomInputType)
		/* if err != nil {
			continue
		} */
		pass = append(pass, pas)
	}
	return pass, nil
}
